package com.sam.lt.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import com.sam.lt.dao.NodeDataRepository;
import com.sam.lt.entity.NodeData;
import com.sam.lt.vo.TreeNodeDataVo;
import com.sam.lt.vo.TreeNodeVo;

@Service
public class NodeDataServiceImpl implements NodeDataService{
	private final Logger logger = LogManager.getLogger(this.getClass());
	
	@Resource
	NodeDataRepository nodeDataRepository;
	
	@Override
	public void batchSave(List<NodeData> list) {
		nodeDataRepository.saveAll(list);
	}

	@Override
	public void batchSaveOrUpdate(Integer nodeId,List<NodeData> list) {
		NodeData probe = new NodeData();
		probe.setNodeId(nodeId);
		Example<NodeData> example = Example.of(probe);
		List<NodeData> oldList = nodeDataRepository.findAll(example);
		nodeDataRepository.deleteAll(oldList);
		
		batchSave(list);
	}

	@Override
	public TreeNodeDataVo getNodeData(Integer nodeId) {
		NodeData probe = new NodeData();
		probe.setNodeId(nodeId);
		Example<NodeData> example = Example.of(probe);
		List<NodeData> nodeDataList = nodeDataRepository.findAll(example);
		
		return TreeNodeDataVo.convertFromNodeData(nodeDataList);
	}

	@Override
	public void hangUpTree(TreeNodeVo branch) {
		if(branch == null) {
			logger.warn("when hangUpTree,branch is null");
			return ;
		}
		TreeNodeDataVo dataVo = getNodeData(branch.getId()); //query node data
		if(dataVo != null && dataVo.getData() != null) { //if has data,hang-up tree
			for(Map<String,String> item : dataVo.getData()) {
				branch.getData().putAll(item);
			}
		}
		
		if(branch.getChildren() != null) {
			for(TreeNodeVo childVo : branch.getChildren()) {
				hangUpTree(childVo);
			}
		}
	}

}
